package com.example.mybatisplusdemo.service;

import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.model.dto.UserProfileDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserMapper userMapper;
    private final ObjectMapper objectMapper;
    private final UserProfileAnalysisService analysisService;

    public User getUserById(Long userId) {
        return userMapper.selectById(userId);
    }

    public UserProfileDTO getUserProfileData(Long userId) {
        User user = getUserById(userId);
        if (user == null) return null;

        return convertToProfileData(user);
    }

    private UserProfileDTO convertToProfileData(User user) {
        UserProfileDTO data = new UserProfileDTO();
        data.setId(user.getId());
        data.setUsername(user.getUsername());
        data.setEmail(user.getEmail());
        data.setPhone(user.getPhone());
        data.setGender(user.getGender());
        data.setAge(user.getAge());
        data.setPreferredPriceRange(user.getPreferredPriceRange());
        data.setPreferredDepartureTime(user.getPreferredDepartureTime());
        data.setPreferredAirline(user.getPreferredAirline());

        // 解析JSON字段
        data.setPreferences(parseJsonToMap(user.getPreferences()));
        data.setTravelHistory(parseJsonToList(user.getTravelHistory()));
        data.setFavoriteAirports(parseJsonToList(user.getFavoriteAirports()));
        data.setUserTags(parseJsonToList(user.getUserTags()));

        return data;
    }

    public void updateUserData(Long userId, UserProfileDTO data) {
        User user = getUserById(userId);
        if (user == null) return;

        // 更新用户数据
        if (data.getGender() != null) user.setGender(data.getGender());
        if (data.getAge() != null) user.setAge(data.getAge());
        if (data.getPreferredPriceRange() != null) user.setPreferredPriceRange(data.getPreferredPriceRange());
        if (data.getPreferredDepartureTime() != null) user.setPreferredDepartureTime(data.getPreferredDepartureTime());
        if (data.getPreferredAirline() != null) user.setPreferredAirline(data.getPreferredAirline());

        // 更新偏好
        if (data.getPreferences() != null) {
            Map<String, String> existingPrefs = parseJsonToMap(user.getPreferences());
            existingPrefs.putAll(data.getPreferences());
            try {
                user.setPreferences(objectMapper.writeValueAsString(existingPrefs));
            } catch (JsonProcessingException e) {
                // 处理异常
            }
        }

        // 更新旅行历史
        if (data.getTravelHistory() != null) {
            List<String> existingHistory = parseJsonToList(user.getTravelHistory());
            existingHistory.addAll(data.getTravelHistory());
            try {
                user.setTravelHistory(objectMapper.writeValueAsString(existingHistory));
            } catch (JsonProcessingException e) {
                // 处理异常
            }
        }

        // 更新收藏机场
        if (data.getFavoriteAirports() != null) {
            List<String> existingFavorites = parseJsonToList(user.getFavoriteAirports());
            existingFavorites.addAll(data.getFavoriteAirports());
            try {
                user.setFavoriteAirports(objectMapper.writeValueAsString(existingFavorites));
            } catch (JsonProcessingException e) {
                // 处理异常
            }
        }

        // 保存更新
        userMapper.updateById(user);
    }

    public void analyzeUserProfile(Long userId) {
        User user = getUserById(userId);
        if (user != null) {
            analysisService.analyzeUserProfile(user);
            userMapper.updateById(user);
        }
    }

    // JSON解析辅助方法
    private Map<String, String> parseJsonToMap(String json) {
        try {
            if (json == null || json.isEmpty()) return new HashMap<>();
            return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});
        } catch (JsonProcessingException e) {
            return new HashMap<>();
        }
    }

    private List<String> parseJsonToList(String json) {
        try {
            if (json == null || json.isEmpty()) return new ArrayList<>();
            return objectMapper.readValue(json, new TypeReference<List<String>>() {});
        } catch (JsonProcessingException e) {
            return new ArrayList<>();
        }
    }
}